import axios from 'axios'
import { Notification } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'

const service = axios.create({
	baseUrl: process.env.BASE_API,
	timeout: 3000
})

// request拦截器
service.interceptors.request.use(config => {
	if (store.getters.authToken) {
		config.headers['EX_SysAuthToken'] = getToken('EX_SysAuthToken')
	}
	config.headers['Content-Type'] = 'application/x-www-form-ulencoded,charset=utf-8'
	config.headers['Access-Control-Allow-Origin'] = '*'
	return config
}, error => {
	console.log(error) // for debug
	Promise.reject(error)
})

// response拦截器
service.interceptors.response.use(
  response => {
	if (response.status !== 200) {
		switch (response.status) {
			case 500:
				Notification({
					title: response.status,
					message: response.errorCode || '系统服务异常，请联系管理员',
					type: 'error',
					duration: 5 * 1000
				})
				break
			case 404:
				Notification({
					title: response.status,
					message: response.errorCode || '请求页面不存在，请联系管理员',
					type: 'error',
					duration: 5 * 1000
				})
				break
			case 0:
				Notification({
					title: response.status,
					message: response.errorCode || '服务器没有响应，请联系管理员',
					type: 'error',
					duration: 5 * 1000
				})
				break
			default:
				Notification({
					title: response.status,
					message: 'response.errorCode || 系统处理异常，请联系管理员',
					type: 'error',
					duration: 5 * 1000
				})
		}
		console.log(response) // for debug
		return
	}
	return response
},
  error => {
	console.log('err: ' + error) // for debug
	Notification({
		message: error.message,
		type: 'error',
		duration: 5 * 1000
	})
	return Promise.reject(error)
}
)
export default service
